<template>
    <!-- 年度考核题库 题库列表-->
    <!-- <TagsView /> -->

    <div class="container">
      <!-- <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item >年度考核题库</el-breadcrumb-item>
      </el-breadcrumb> -->

      <el-row class="" style="margin-bottom: 20px">
        <el-col :span="10" align="left">
          <el-input
            v-model="searchFrom.name"
            placeholder="考核指标名称"
            style="width: 150px; margin-right: 15px"
            clearable
          />
          <el-button class="ordinary" @click="search()">搜索</el-button>
        </el-col>
        <el-col :span="14" align="right">
          <el-button class="ordinary" @click="getExportBtn()" v-limit="'KHGL:SZHKH:NDKHTK:EXPERT'">批量导出</el-button>
          <el-button type="danger" @click="handleDetect()" v-limit="'KHGL:SZHKH:NDKHTK:DELETE'">删除</el-button>
          <el-button type="primary" @click="lock()" v-limit="'KHGL:SZHKH:NDKHTK:LOCK'">锁定</el-button>
          <el-button type="primary" @click="unlock()" v-limit="'KHGL:SZHKH:NDKHTK:UNLOCK'">解锁</el-button>
          <el-button class="lock" @click="handleCopy()" v-limit="'KHGL:SZHKH:NDKHTK:COPY'">复制</el-button>
          <el-button type="primary" @click="handleAdd()" v-limit="'KHGL:SZHKH:NDKHTK:NEW'">新建</el-button>
        </el-col>
      </el-row>
      <div>
        <el-table
          ref="inOrderTable"
          :data="data.table_list"
          style="width: 100%"
          row-key="id"
          v-loading="data.table_loading"
          @selection-change="selectionChange"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        >
          <el-table-column
            type="selection"
            width="55"
            align="center"
            :reserve-selection="false"
          />
          <el-table-column prop="name" label="考核名称" align="center" />
          <el-table-column prop="age" label="年度" align="center" width="80" />
          <el-table-column prop="counts" label="题目数量" align="center" />
<!--          <el-table-column prop="standardAddPoints" label="总分" align="center" width="80" >-->
          <el-table-column label="总分" align="center" width="80" >
                <template #default="scope">
                  <span span   v-if="scope.row.standardPlusPoints != 0">{{ scope.row.standardAddPoints}} + {{scope.row.standardPlusPoints}}</span>
                  <span span   v-if="scope.row.standardPlusPoints == 0">{{ scope.row.standardAddPoints + scope.row.standardPlusPoints}}</span>
                </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" align="center" />
          <el-table-column prop="modifyUsername" label="操作人" align="center" />
          <el-table-column prop="modifyTime" label="更新时间" align="center" />
          <el-table-column prop="lockFlag_text" label="状态" align="center" />
          <el-table-column prop="address" label="操作" align="center" width="180" fixed="right">
            <template #default="scope">
              <el-button @click="giveScoreManage(scope.row)" v-if="scope.row.lockFlag == '1'">查看</el-button>
              <el-button type="primary" @click="handleEdit(scope.row,'edit')" v-if="scope.row.lockFlag != '1'">编辑</el-button>
              <el-button
                type="primary"
                v-if="scope.row.lockFlag != '1'"
                @click="giveScoreManage(scope.row)"
                v-limit="'KHGL:SZHKH:NDKHTK:MANAGE'"
                >管理</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <div class="example-pagination-block">
            <el-pagination
              :current-page="searchFrom.current"
              :page-size="searchFrom.size"
              :page-sizes="[10, 20, 30, 40,50,100]"
              background
              layout="prev, pager, next ,total,sizes,jumper"
              :total="data.page.total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
          />
      </div>
      </div>

      <el-dialog
        v-model="data.modalVisible"
        :show-close="false"
        width="1100px"
        :style="'min-height: 400px;'"
        :title="data.opType == 'add' ? '新增' : data.opType == 'copy' ? '复制' : data.opType == 'edit' ? '编辑' : '查看'"
        @closed="close"
      >
      <el-form :model="form" ref="ruleFormRef" label-position="right" label-width="100px" :inline="true"
        :rules="rules" status-icon class="demo-form-inline">
        <el-form-item label="考核名称:" prop="name"  style="width: 40%">
          <el-input  v-model="form.name" maxlength="20" placeholder="请输入" show-word-limit  style="width: 100%;" :disabled="data.opType == 'look'"/>
        </el-form-item>
        <el-form-item label="年度:" prop="age"  style="width: 39%">
          <!-- <el-input  v-model="form.age" maxlength="19" placeholder="请输入"  style="width: 100%;"/> -->
          <el-date-picker style="width: 100%;"  :disabled="data.opType == 'look'"
            v-model="form.age"
            type="year"
            value-format="YYYY"
            placeholder="选择年">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注:"   style="width: 80%"  prop="remark">
          <el-input type="textarea"  v-model="form.remark" placeholder="请输入"  :autosize="{ minRows: 3 }"  :disabled="data.opType == 'look'" maxlength="100" show-word-limit />
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button size="small"  @click="close()">关闭</el-button>
        <el-button size="small" type="primary" @click="save()" v-show="data.opType != 'look'">保存</el-button>
      </span>
    </template>
     </el-dialog>

      <!-- <scoreManModal
        v-model:visible="data.scoreManVisible"
        :handleRow="data.handleRowData"
        :apiPackage="apiPackage"
      ></scoreManModal> -->
    </div>
  </template>
  <script lang="ts" setup>
  import { reactive, ref } from "vue";
  // import Table from '../../../components/indexTable.vue'
  import { dataDictionary } from "@/api/dict";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRoute, useRouter } from "vue-router";
import * as api from "../../api/digital";

  const searchFrom = reactive({
    //查询
    name: "",
    size:10,
    current:1,
  });
  // const refreshPage:any=inject('refreshPage', Function, true);
  let standardType = ref("1"); //该参数决定显示的是中交还是中咨的标准库纸指标
  const route = useRoute();
  const router = useRouter();
  const inOrderTable = ref()

  standardType.value = route.meta.type as string;
  const apiPackage = reactive({
    detail: "scoreManDetailRequest",
    score: "updateScoreRuleRequest",
    insert: "insertItemSetRequest",
    update: "updateItemSetRequest",
    delete: "deleteItemSetRequest",
  });

  const pagination = reactive({  //分页器信息
      pageSize:10,
      currentPage:1,
  })
  //弹出框form
  const form = reactive({
    name:'',
    age:'',
    remark:'',
    id:'',
  })
  const rules = reactive({
      name: [
        { required: true, message: '请输入考核名称', trigger: 'blur' },
      ],
      age: [
        { required: true, message: '请选择年度', trigger: 'blur', },
      ]
      })

  let data = reactive<any>({
    table_list: [],
    modalVisible: false,
    opType: "add", //add,edit,copy
    handleRowData: null, //正在处理的行数据
    scoreManVisible: false,
    table_loading: false,
    page: { page: 1, limit: 10, total: 0 },
  });
  const dictDatas = reactive({
    dict_indexTypes: [],
    dict_indexNames: [],
    dict_scoreTypes: [],
    dict_scoreMethods: [],
    dict_scoreSources_zj: [],
    dict_scoreSources_zz: [],
    dict_scoreCompose_zj: [],
    dict_scoreCompose_zz: [],
  }); //字典值
  let selectedRows = ref<any>([]);
  const search = () => {
    //搜索
    gettargetlist();
  };

  const getExportBtn = () => {
    ElMessageBox.confirm("确定要批量导出吗?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(() => {
    //批量导出
    api
      .exportStandardIndexRequest({
        name:searchFrom.name
      })
    });
  };
  const selectionChange = (arr) => {
    //选中
    selectedRows.value = arr;
  };
  //锁定
  const lock = () =>{
    if (selectedRows.value.length === 0) {
      ElMessage({
        message: "请选择数据后锁定！",
        type: "warning",
      });
    }else {
      ElMessageBox.confirm("确定要锁定选中数据吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        // let sel_ids=selectedRows.value.map(item=>{return item.id});
        let ids = [] as any
        selectedRows.value.forEach(e  => {
          ids.push(e.id)
        });
        api
          .hadLock({
            ids: ids
          })
          .then((res) => {
            if (res.data.code == 200) ElMessage.success("锁定成功");
            gettargetlist();
          });
      });
    }
  }
  //解锁
  const unlock = () =>{
    if (selectedRows.value.length === 0) {
      ElMessage({
        message: "请选择数据后解锁！",
        type: "warning",
      });
    }else {
      ElMessageBox.confirm("确定要解锁选中数据吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        // let sel_ids=selectedRows.value.map(item=>{return item.id});
        let ids = [] as any
        console.log('解锁value',selectedRows.value);

        selectedRows.value.forEach(e  => {
          ids.push(e.id)
        });

        console.log('解锁1 ids',ids);

        api
          .hadUnLock({
            ids: ids
          })
          .then((res) => {
            if (res.data.code == 200) ElMessage.success("解锁成功");
            gettargetlist();
          });

          // ids.length = []
      });
    }
  }
  //批量删除
  const handleDetect = () => {
    if (selectedRows.value.length === 0) {
      ElMessage({
        message: "请选择数据后删除！",
        type: "warning",
      });
    }else {
      ElMessageBox.confirm("确定要删除选中数据吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        // let sel_ids=selectedRows.value.map(item=>{return item.id});
        let ids = [] as any
        selectedRows.value.forEach(e  => {
          ids.push(e.id)
        });
        api
          .deleteStandardIndexRequest({
            ids: ids
          })
          .then((res) => {
            if (res.data.code == 200) ElMessage.success("删除成功");
            gettargetlist();
          });
      });
    }
  };
  const ruleFormRef = ref()
  //关闭弹窗
  const close = () =>{
    data.modalVisible = false
    ruleFormRef.value.resetFields()
    form.name = ''
    form.age = ''
    form.remark = ''
    form.id = ''
  }

  //保存
  const save = async () =>{
  await ruleFormRef.value.validate((valid) => {
    if (valid) {
      console.log('save',form);
      if(data.opType == "edit"){
        api.updateAnnual(form).then(res =>{
          if(res.data.code ==200){
            ElMessage({
              message: "编辑成功",
              type: "success",
            });
            gettargetlist();
          }
        })
      }else{
        api.addAnnual(form).then(res =>{
          if(res.data.code ==200){
            ElMessage({
              message: "新增成功",
              type: "success",
            });
            gettargetlist();
          }
        })
      }
      close()
    }
  })
  }
  const getLockBtn = () => {
    //复制
  };
  const handleAdd = () => {
    //新增
    data.opType = "add";
    data.modalVisible = true;
  };
  //编辑
  const handleEdit = (item,type) => {
    data.opType = type;
    form.age = item.age
    form.name = item.name
    form.remark = item.remark
    form.id = item.id
    console.log('item',item,'form=>',form);
    // data.handleRowData = item;

    data.modalVisible = true;
  };
  //点击复制按钮------复制
  const handleCopy = () => {
    if (selectedRows.value.length !== 1) {
      ElMessage({
        message: "请选择一条数据复制",
        type: "warning",
      });
    } else if(selectedRows.value.length > 1){
      ElMessage({
        message: "只允许选择一条数据复制",
        type: "warning",
      });
    }else{
      data.opType = "copy";
      // data.handleRowData = selectedRows.value[0];
      data.modalVisible = true;
      form.age = selectedRows.value[0].age
      form.name = selectedRows.value[0].name
      form.remark = selectedRows.value[0].remark
    }
  };
  const giveScoreManage = (item) => {
    //评分管理
    // data.handleRowData = item;
    // data.scoreManVisible = true;
    router.push({
    path: "/examineManage/digitalExamine/manage",
    query: {
      bankId:item.id,
      status: item.lockFlag_text
    },
  });
  };
  const getDictDatas = () => {
    return new Promise((resolve, reject) => {
      data.table_loading = true;
      let dictIds = [
        "KHGL_CLASS_INDEX_NAME_CODE",
        "KHGL_INDEX_TYPE_CODE",
        "KHGL_SCORE_METHOD_CODE",
        "KHGL_SCORE_TYPE_CODE",
        "KHGL_ZJ_EXAMINE_SCORE_METHOD_CODE",
        "KHGL_ZZ_EXAMINE_SCORE_METHOD_CODE",
      ];
      dataDictionary(dictIds).then((res) => {
        let response = res.data.data;
        dictDatas.dict_indexTypes = response.KHGL_INDEX_TYPE_CODE;
        dictDatas.dict_indexNames = response.KHGL_CLASS_INDEX_NAME_CODE;
        dictDatas.dict_scoreTypes = response.KHGL_SCORE_TYPE_CODE;
        dictDatas.dict_scoreMethods = response.KHGL_SCORE_METHOD_CODE;
        dictDatas.dict_scoreSources_zj = response.KHGL_ZJ_EXAMINE_SCORE_METHOD_CODE;
        dictDatas.dict_scoreSources_zz = response.KHGL_ZZ_EXAMINE_SCORE_METHOD_CODE;
        if (standardType.value === "1") {
          //中交
          response.KHGL_ZJ_EXAMINE_SCORE_METHOD_CODE.map((item) => {
            dictDatas.dict_scoreCompose_zj = dictDatas.dict_scoreCompose_zj.concat(
              item.children
            );
          });
        } else {
          response.KHGL_ZZ_EXAMINE_SCORE_METHOD_CODE.map((item) => {
            dictDatas.dict_scoreCompose_zz = dictDatas.dict_scoreCompose_zz.concat(
              item.children
            );
          });
        }

        resolve(1);
      });
    });
  };
  // let table_list=reactive<any>([]);
  const gettargetlist = () => {
    //获取标准指标库列表
    data.table_loading = true;
    api
      .getAnnualList({
        ...searchFrom,
      })
      .then((res) => {
        console.log('res',res);
        data.table_loading = false;
        data.table_list = res.data.data.records;
        data.page.total = res.data.data.total;
      });
      selectedRows.value = []
      inOrderTable.value.clearSelection()
  };
   //分页操作
  const handleSizeChange = (val) =>{
    pagination.pageSize = val
    searchFrom.size = val
    gettargetlist()
  }

  const handleCurrentChange = (val) =>{
    pagination.currentPage = val
    searchFrom.current = val
    gettargetlist()
  }
  getDictDatas().then(() => {
    gettargetlist();
  });
  </script>
  <style lang="scss" scoped>
  .container {
    background-color: white;
    padding: 20px;
    overflow-y: auto;
  }

  // :deep(.el-dialog__body) {
  //   padding: 0 !important
  // }
  :deep(.el-dialog__body) {
    padding: 0;
  }

  .dialogCloseBtn {
    position: absolute;
    top: 20px;
    right: 20px;
  }

  // .el-col {
  //   line-height: 60px;
  // }

  .pageName {
    font-weight: 700;
  }

  .el-form-item {
    .el-input {
      width: 100px;
    }

    .el-select {
      width: 100px;
    }
  }

  :deep(.demo-tabs > .el-tabs__content) {
    max-height: 500px;
    overflow-y: scroll;
    scrollbar-width: none;
    /* Firefox */
    -ms-overflow-style: none;
    /* IE 10+ */
  }

  :deep(.demo-tabs > .el-tabs__content::-webkit-scrollbar) {
    display: none;
    /* Chrome Safari */
  }
  .demo-form-inline .el-form-item {
  width: 30%;
}

:deep(.labelHeight .el-form-item__label) {
  line-height: 20px;
}
:deep .el-breadcrumb{
  margin-bottom: 15px;
  span{
    color: #606266;
  }
}
  </style>
